package com.yssoft.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.yssoft.entity.core.TAccounts;
import com.yssoft.entity.core.TCode;
import com.yssoft.entity.core.TDepartment;
import com.yssoft.entity.core.TPersonnel;
import com.yssoft.entity.production.TBatch;
import com.yssoft.entity.production.TLabelApply;
import com.yssoft.entity.production.TLabels;
import com.yssoft.service.core.AccountsService;
import com.yssoft.service.core.PersonService;
import com.yssoft.service.inspection.InspReportService;
import com.yssoft.service.production.BatchService;
import com.yssoft.service.production.LabelApplyService;
import com.yssoft.service.production.LabelsService;
import com.yssoft.service.production.WorkSheetService;
import com.yssoft.utils.ExcelUtil;
import com.yssoft.utils.UserHelper;

/**
 * @类名称: LabelController
 * @类描述: 标签审批管理控制器
 * @作者: 王永宁
 * @创建时间:2018年5月11日 上午11:21:50
 */
@Controller
@RequestMapping("/label")
public class LabelController {
    private static Logger logger = Logger.getLogger(LabelController.class);
    @Resource
    private LabelApplyService labelApplyService;

    @Resource
    private LabelsService labelsService;


    @Resource
    private BatchService batchService;

    @Resource
    private PersonService personService;

    @Resource
    private AccountsService accountService;

    @Resource
    private WorkSheetService workSheetService;

    //文件位置
    private static String WORKDIR;

    @Value("${local_path}")
    public void setWorkdir(String workdir) {
        WORKDIR = workdir;
    }

    /**
     * 跳转到标签管理页面
     *
     * @return
     */
    @RequestMapping("/labelPage")
    public String findlabelPage() {
        return "label/labelList";
    }

    /**
     * 跳转到标签审批页面
     *
     * @return
     */
    @RequestMapping("/labelApprovalPage")
    public String labelApprovalPage(Model model) {
        return "label/labelApprovalList";
    }

    /**
     * 获取标签申请数据
     *
     * @param page
     * @param limit
     * @return
     */
    @RequestMapping("/findLabelPage")
    @ResponseBody
    public JSONObject findLabelPage(@RequestParam(name = "page", defaultValue = "0") int page, @RequestParam(name = "limit", defaultValue = "10") int limit, String code, String creatorName, String stat) {
        JSONObject jsonObject = labelApplyService.queryLabelPage(page, limit, code, creatorName, stat);
        return jsonObject;
    }

    /**
     * 监管菜单不能用企业信息过滤
     * 跳转到标签申请信息页面
     *
     * @return
     */
    @RequestMapping("labelEditPage")
    public String labelEditPage(String labelId, Model model, HttpServletRequest request) {
        if (labelId != null && labelId.trim().length() > 0) {
            //修改
            TLabelApply label = labelApplyService.queryLabelApplyById(labelId);
            Map<String, Object> product = batchService.queryBatchById(label.gettBId(), request);
            TBatch batch = batchService.getOneById(label.gettBId());
            int count = batch.getpQuantity().intValue();
            model.addAttribute("count", count);
            model.addAttribute("label", label);
            model.addAttribute("product", product);
            model.addAttribute("batch", batch);
        }

        return "label/labelEdit";
    }

    /**
     * 跳转到标签申请信息详情页面
     *
     * @return
     */
    @RequestMapping("labelViewPage")
    public String labelViewPage(String labelId, Model model, HttpServletRequest request) {
        if (labelId != null && labelId.trim().length() > 0) {
            TLabelApply label = labelApplyService.queryLabelApplyById(labelId);
            Map<String, Object> product = batchService.queryBatchById(label.gettBId(), request);
            TBatch batch = batchService.getOneById(label.gettBId());
            int count = batch.getpQuantity().intValue();
            model.addAttribute("count", count);
            model.addAttribute("label", label);
            model.addAttribute("product", product);
            model.addAttribute("batch", batch);
        }

        return "label/labelView";
    }

    /**
     * 保存标签审批信息
     *
     * @param
     * @return
     */
    @RequestMapping("saveLabel")
    @Transactional
    public String saveLabel(String id, String content, String open, String grantQuantity, HttpServletRequest request) {
        if (open.contains("true")) {
            TLabelApply labelApply = labelApplyService.queryLabelApplyById(id);
            Map<String, Object> batch = batchService.queryBatchById(labelApply.gettBId(), request);
            labelApply.setStat("1");
            labelApply.setContent(content);
            labelApply.setGrantQuantity(new BigDecimal(grantQuantity));
            labelApplyService.updateLabelApply(labelApply);
            for (int i = 0; i < Integer.parseInt(grantQuantity); i++) {
                TLabels label = new TLabels();
                label.setCreateTime(new Date());
                label.setDeleteFlag("0");
                label.settEId(labelApply.gettEId());
                label.settLabelAppId(Integer.valueOf(id));
                label.setCreatorId(labelApply.getCreatorId());
                label.setCreatorName(labelApply.getCreatorName());
                label.setLabelStat("0");
                label.setDeptId(labelApply.getDeptId());
                label.setTraceType((String) batch.get("traceability_type"));
                labelsService.save(label);
            }


        } else {
            TLabelApply labelApply = labelApplyService.queryLabelApplyById(id);
            labelApply.setStat("2");
            labelApply.setContent(content);
            labelApplyService.updateLabelApply(labelApply);
        }
        return "redirect:labelApprovalPage";
        // return "redirect:labelPage";
    }

    /**
     * 跳转到标签查看页面
     * 王永宁
     *
     * @return
     */
    @RequestMapping("/labelCheckPage")
    public String labelCheckPage(String labelId, Model model) {
        model.addAttribute("labelId", labelId);
        return "label/labelCheck";
    }

    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletResponse res, String labelId, HttpServletRequest request) {
        logger.debug("当前labelId=" + labelId);
        //获取数据
        List<Map<String, Object>> data = labelApplyService.exportExcel(request, labelId);
        //设置导出列
        String[] headers = {"条形码值", "下载地址"};
        String exportExcelName = "溯源源码";
        //获得workbook
        Workbook wb = ExcelUtil.baseExportExcel(data, headers, exportExcelName);
        //执行导出数据流
        if (wb != null) {
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                wb.write(os);
                byte[] content = os.toByteArray();
                InputStream is = new ByteArrayInputStream(content);
                // 设置response参数，可以打开下载页面
                res.reset();
                res.setContentType("application/vnd.ms-excel;charset=utf-8");
                res.setHeader("Content-Disposition", "attachment;filename=" + new String((exportExcelName + ".xls").getBytes(), "iso-8859-1"));
                ServletOutputStream out = res.getOutputStream();
                bis = new BufferedInputStream(is);
                bos = new BufferedOutputStream(out);
                byte[] buff = new byte[2048];
                int bytesRead;
                // Simple read/write loop.
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);

                }
            } catch (Exception e) {
                logger.debug("当前labelId=" + labelId + ",Exception=" + e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    if (bis != null) {
                        bis.close();
                    }
                    if (bos != null) {
                        bos.close();
                    }
                } catch (IOException e) {
                    logger.debug("当前labelId=" + labelId + ",IOException=" + e.getMessage());
                    e.printStackTrace();
                }
            }

        }
    }


    @RequestMapping("labelCheckPage1")
    @ResponseBody
    public JSONObject labelCheckPage1(@RequestParam(name = "page", defaultValue = "0") int page, @RequestParam(name = "limit", defaultValue = "10") int limit, String labelId, Model model, HttpServletRequest request) {
        JSONObject jsonObject = labelsService.selectLabelList(page, limit, labelId);
        return jsonObject;
    }

    /**
     * 跳转到按加工单查询页面
     *
     * @return
     */
    @RequestMapping("/exportByWorksheet")
    public String exportByWorksheet(String tbId, Model model) {
        model.addAttribute("tbId", tbId);
        return "label/exportByWorksheetLabelList";
    }

    @RequestMapping("/findWorksheetPage")
    @ResponseBody
    public JSONObject findWorksheetPage(@RequestParam(name = "page", defaultValue = "0") int page, @RequestParam(name = "limit", defaultValue = "10") int limit, String tbId) {
        JSONObject jsonObject = workSheetService.findPageByTbId(page, limit, tbId);
        return jsonObject;
    }

    @RequestMapping("/exportLabel")
    public void exportLabel(HttpServletResponse res, String workSheetId, HttpServletRequest request) {
        logger.debug("当前workSheetId=" + workSheetId);
        //获取数据
        List<Map<String, Object>> data = labelApplyService.exportLabel(request, workSheetId);
        //设置导出列
        String[] headers = {"条形码值", "下载地址"};
        String exportExcelName = "溯源源码";
        //获得workbook
        Workbook wb = ExcelUtil.baseExportExcel(data, headers, exportExcelName);
        //执行导出数据流
        if (wb != null) {
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                wb.write(os);
                byte[] content = os.toByteArray();
                InputStream is = new ByteArrayInputStream(content);
                // 设置response参数，可以打开下载页面
                res.reset();
                res.setContentType("application/vnd.ms-excel;charset=utf-8");
                res.setHeader("Content-Disposition", "attachment;filename=" + new String((exportExcelName + ".xls").getBytes(), "iso-8859-1"));
                ServletOutputStream out = res.getOutputStream();
                bis = new BufferedInputStream(is);
                bos = new BufferedOutputStream(out);
                byte[] buff = new byte[2048];
                int bytesRead;
                // Simple read/write loop.
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);

                }
            } catch (Exception e) {
                logger.debug("当前workSheetId=" + workSheetId + ",Exception=" + e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    if (bis != null) {
                        bis.close();
                    }
                    if (bos != null) {
                        bos.close();
                    }
                } catch (IOException e) {
                    logger.debug("当前workSheetId=" + workSheetId + ",IOException=" + e.getMessage());
                    e.printStackTrace();
                }
            }

        }
    }
}
